package com.lzy.permission.handler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import com.lzy.web.form.JsonResponse4Ext;

/**
 * 验证失败返回json
 * For Ext 登陆
 * @author pwz
 *
 */
public class JsonAuthenticationFailureHandler implements AuthenticationFailureHandler {

	public JsonAuthenticationFailureHandler() {
	}

	public void onAuthenticationFailure(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException exception)
			throws IOException, ServletException {
		
		MappingJacksonHttpMessageConverter converter = new MappingJacksonHttpMessageConverter();
		HttpOutputMessage outputMessage = new ServletServerHttpResponse(response);
		
		JsonResponse4Ext ext = new JsonResponse4Ext(false);
		ext.setErrorMessages(exception.getMessage());
		
		converter.write(ext, MediaType.APPLICATION_JSON, outputMessage);
	}
	
}
